package com.itheima.aop;


import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpLoginLog;
import com.itheima.pojo.LoginInfo;
import com.itheima.pojo.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Slf4j
@Component
public class LoginAspect {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private OperateLogMapper operateLogMapper;


    @Around("execution(* com.itheima.controller.LoginController.login(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {

//        1.计算开始时间
        long begin = System.currentTimeMillis();

//        2.运行目标方法
        Object result = pjp.proceed();

//        3. 计算耗时
        long end = System.currentTimeMillis();
        long costTime = end - begin;
        log.info("耗时时间 :  {}", end - begin);

//        4.获取用户名
        Emp emp = (Emp) pjp.getArgs()[0];
        String username = emp.getUsername();

//        5.获取登录密码
        String password = emp.getPassword();

//        6.获取用户操作时间
        LocalDateTime loginTime = LocalDateTime.now();

//        7.是否登录成功
        Result res = (Result) result;
        Integer code = res.getCode();
        short isSuccess = code.shortValue();

//        8.jwt令牌
        LoginInfo data = (LoginInfo) res.getData();
        String jwt = isSuccess == 1 ? data.getToken() : null;

//        9.有参构造对象
        EmpLoginLog empLoginLog = new EmpLoginLog(null, username, password, loginTime, isSuccess, jwt, costTime);

//        10.调用Mapper层插入信息
        operateLogMapper.add(empLoginLog);

        return result;
    }

}
